"""
对话相关的数据模型
- ChatSession: 对话会话表，记录用户的对话会话
- ChatMessage: 对话消息表，记录会话中的具体消息
"""

from datetime import datetime, UTC
from sqlalchemy import Column, String, DateTime, Integer, JSON, ForeignKey, Enum, text
from sqlalchemy.orm import relationship
import enum
from dao.postgresql_connect import Base

class SessionStatus(enum.Enum):
    """会话状态枚举"""
    ACTIVE = "active"
    ARCHIVED = "archived"

class ChatSession(Base):
    """对话会话表"""
    __tablename__ = 'chat_sessions'

    id = Column(String(36), primary_key=True)
    user_id = Column(String(36), ForeignKey('users.id'), nullable=False, comment='用户ID')
    app_id = Column(String(36), ForeignKey('apps.id'), nullable=False, comment='应用ID')
    title = Column(String, nullable=False, comment='会话标题')
    status = Column(Enum(SessionStatus), default=SessionStatus.ACTIVE, nullable=False, comment='会话状态')
    session_metadata = Column(JSON, default=dict, comment='会话元数据')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    user = relationship('User', back_populates='chat_sessions')
    app = relationship('App', back_populates='chat_sessions')
    messages = relationship('ChatMessage', back_populates='session', cascade='all, delete-orphan')

class ChatMessage(Base):
    """对话消息表"""
    __tablename__ = 'chat_messages'

    id = Column(String(36), primary_key=True)
    session_id = Column(String(36), ForeignKey('chat_sessions.id'), nullable=False, comment='会话ID')
    role = Column(String, nullable=False, comment='消息角色(user/assistant)')
    content = Column(String, nullable=False, comment='消息内容')
    tokens = Column(Integer, nullable=False, comment='消息token数')
    message_metadata = Column(JSON, default=dict, comment='消息元数据')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')

    # 关系
    session = relationship('ChatSession', back_populates='messages') 